import { View, Image, Text } from '@tarojs/components'
import { useState, useEffect } from 'react'
import LgButton from '@/pages/components/button'
import LgCell from '@/pages/components/cell'
import Header from '@/pages/components/navCustomBar'
import { LgPopLayer } from '@/pages/components/popLayer'
import Taro from '@tarojs/taro'
import { AtSegmentedControl } from 'taro-ui'
import Loading from '../component/load'
import { HttpGet, HttpDelete } from '@/network/servers'
import dayjs from 'dayjs'
import Utils from '@/utils/index'
import { connect } from 'react-redux'
import { getBrowserController, getNet, getStorage, getWxSDKParams } from '@/pages/components/utils';
import '../../images/public/style.css'
import './index.scss'
const storage = getStorage()
var wx = require('weixin-js-sdk')
const {
  getQueryVariable,
  getDateGap,
} = Utils


const requireContext = require.context("../../images/fileIcon", true, /^\.\/.*\.svg$/);
const svgs = requireContext.keys().map(requireContext);
const keys = requireContext.keys()
let fileObj = {}

keys.map((item, index) => {
  let str = item.replace('./', "").replace('.svg', "")
  fileObj[str] = svgs[index]
})


function App(props) {

  let {
    userInfo,
    baseUrl
  } = props



  const getToken = () => {
    if (getQueryVariable('env') === 'weapp') {
      return getQueryVariable('lg_tk')
    } else {
      return storage.get('token') || getQueryVariable('lg_tk')
    }
  }

  const [init, setInit] = useState(false)
  const [title, setTitle] = useState('课程')
  const [className, setClassName] = useState('')
  const [height, setHeight] = useState(0);
  const [week, setWeek] = useState(0);//周几
  const [month, setMonth] = useState(0);//月份
  const [day, setDay] = useState(0);//日期
  const [scheduleDay, setScheduleDay] = useState('');//课程时间
  const [address, setAddredd] = useState('');//课程地点
  const [duration, setDuration] = useState<any>(0);//日程时长
  const [startTime, setStartTime] = useState('');//开始时间
  const [start, setStart] = useState('');//开始时间
  const [endTime, setEndTime] = useState('');
  const weeks = {
    1: '周一',
    2: '周二',
    3: '周三',
    4: '周四',
    5: '周五',
    6: '周六',
    7: '周日',
  };

  const getCommonData = () => {
    if (Utils.getQueryVariable('env') === 'weapp' || window.__wxjs_environment === 'miniprogram') {
      // 小程序端的h5
      if (!baseUrl) {

      } else {
        //应用内跳转
        let instance = Taro.getCurrentInstance()
        const browserController = getBrowserController()
        let height = browserController.getStatusBarHeight()
        setHeight(height)
        if (instance.router?.params) {
          let params = instance.router.params
          setTitle(decodeURIComponent(params.title));
          setAddredd(decodeURI(params.address));
          setClassName(decodeURI(params.class));
          setDuration(params.times);
          let startDate = params.scheduleDate + ' ' + params.startTime;
          let endDate = params.scheduleDate + ' ' + params.endTime;
          let durationTime = getDateGap(startDate, endDate);
          // let durationTime = dayjs(endDate).diff(startDate,'h');
          // console.log(durationTime,'durationTime');
          let week = dayjs(startDate).day();
          let month = dayjs(startDate).month();
          let day = dayjs(startDate).date();
          setStartTime(startDate);
          setStart(params.startTime ? params.startTime : '');
          setEndTime(params.endTime ? params.endTime : '');
          setScheduleDay(params.scheduleDate);
          setWeek(week);
          setMonth(month + 1);
          setDay(day);
          // setDuration(durationTime);
          setInit(true);

          if (JSON.stringify(userInfo) === '{}') {
            goHome();
            return;
          }


        }
      }
    } else {
      // app内 1.应用内跳转(不需要获取通知地址和用户信息) 2.直接跳转
      let instance = Taro.getCurrentInstance()
      const browserController = getBrowserController()
      let height = browserController.getStatusBarHeight()
      setHeight(height)
      if (instance.router?.params) {
        let params = instance.router.params
        setTitle(decodeURIComponent(params.title));
        setAddredd(decodeURI(params.address));
        setClassName(decodeURI(params.class));
        setDuration(params.times);
        let startDate = params.scheduleDate + ' ' + params.startTime;
        let endDate = params.scheduleDate + ' ' + params.endTime;
        let durationTime = getDateGap(startDate, endDate);
        // let durationTime = dayjs(endDate).diff(startDate,'h');
        // console.log(durationTime,'durationTime');
        let week = dayjs(startDate).day();
        let month = dayjs(startDate).month();
        let day = dayjs(startDate).date();
        setStartTime(startDate);
        setStart(params.startTime ? params.startTime : '');
        setEndTime(params.endTime ? params.endTime : '');
        setScheduleDay(params.scheduleDate);
        setWeek(week);
        setMonth(month + 1);
        setDay(day);
        setInit(true);
        // setDuration(durationTime);

        if (JSON.stringify(userInfo) === '{}') {
          goHome();
          return;
        }
      }
    }
  }

  const goBack = () => {
    Taro.redirectTo({
      url: '/pages/scheduleApp/index?id='
    })
  }

  const initWxSdk = async () => {
    const params = getWxSDKParams(['previewImage', 'getLocation'])
    wx.config(params);
    wx.ready(function () {
      // config信息验证后会执行 ready 方法，所有接口调用都必须在 config 接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在 ready 函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在 ready 函数中。
      console.log('ready')
    });
    wx.error(function (res) {
      // config信息验证失败会执行 error 函数，如签名过期导致验证失败，具体错误信息可以打开 config 的debug模式查看，也可以在返回的 res 参数中查看，对于 SPA 可以在这里更新签名。
      console.log(res)
    });
  }

  useEffect(() => {
    document.title = '日程详情'
    if (window.__wxjs_environment === 'miniprogram') {
      initWxSdk()
    }
    getCommonData()
    return () => {
      if (Utils.getSystemInfo() === 'weapp') {
        document.title = '日程详情'
        window.getScheduleList && typeof window.getScheduleList === 'function' && window.getScheduleList()
      }
    }
  }, []);

  useEffect(() => {
    if (JSON.stringify(userInfo) === '{}') {
      goHome();
    }
  }, [userInfo])

  //返回首页
  const goHome = () => {
    Taro.navigateTo({
      url: '/pages/scheduleApp/index?id='
    });
  }

  if (!init) {
    return (
      <View>
        <Loading content='加载中' isOpened={true} />
      </View>
    )
  }

  return (
    <View className="scheduleDetail">
      {
        Utils.getQueryVariable('env') === 'weapp' || window.__wxjs_environment === 'miniprogram' ?
          "" :
          <Header
            className='header-top'
            mainTitle='日程详情'
            mainTitleBlod={false}
            isTitlePositionLeft={true}
            needMainIcon={process.env.TARO_ENV === 'weapp' ? false : true}
            onClick={Taro.getCurrentInstance().router?.params.from ? goBack : ''}
          />
      }

      <View className='schedule-container'>
        <View className='header'>
          <View className='title'>{title}</View>
          <View className='line'></View>
          <View className='time-info'>
            <View className='time-info-left'>
              <Text className='days'>{month}月{day}日 {weeks[week]}</Text>
              <Text className='times'>{start}</Text>
            </View>
            <View className='duration'>
              <Text style={{ margin: '0 0 0 10px', color: 'rgb(238, 241, 243)' }}>—</Text>
              <View className='duration-time'>
                <Text >{duration}分钟</Text>
              </View>
              <Text style={{ margin: '0 10px 0 0', color: 'rgb(238, 241, 243)' }}>—</Text>
            </View>
            <View className='time-info-right'>
              <Text className='days'>{month}月{day}日 {weeks[week]}</Text>
              <Text className='times'>{endTime}</Text>
            </View>
          </View>
        </View>
        <View className='place-detail'>
          <View className='place'>班级<View className='address '>{className == '无' ? <Text style={{ color: '#999' }}>--</Text> : className}</View></View>
          <View className='line line-long'></View>
          <View className='detail'>地点<View className='describe'>{address == '无' ? <Text style={{ color: '#999' }}>--</Text> : address}</View></View>
        </View>
      </View>
      {/* 适配pad不要返回 */}
      <View className="index-footer">
        <LgButton className="send-btn delete-btn" type='D' onClick={() => goBack()} >返回</LgButton>
      </View>

    </View>
  )
}

const mainProps = ({ commonData }) => {
  return {
    userInfo: commonData.userInfo,
    env: commonData.env,
    noticeAddr: commonData.noticeAddr,
    baseUrl: commonData.baseUrl
  }
}

export default connect(mainProps)(App);
